from pyVim.connect import SmartConnectNoSSL
from pyVmomi import vim
import asyncio


async def create_vm():
    si = SmartConnectNoSSL(host='myhost', user='myuser', pwd='mypassword')
    content = si.RetrieveContent()
    vm_folder = content.rootFolder.childEntity[0]
    resource_pool = content.rootFolder.childEntity[1].resourcePool
    datastore = content.rootFolder.childEntity[1].datastore[0]
    vm_name = "my_vm"
    vmx_path = "[{}] my_vm/my_vm.vmx".format(datastore.summary.name)
    vm_file = vim.vm.FileInfo(logDirectory=None, snapshotDirectory=None, suspendDirectory=None, vmPathName=vmx_path)
    vm_device = vim.vm.device.VirtualDeviceSpec()
    vm_device.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
    vm_device.device = vim.vm.device.VirtualDisk()
    vm_device.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo()
    vm_device.device.backing.fileName = "[{}] my_vm/my_vm.vmdk".format(datastore.summary.name)
    vm_device.device.backing.diskMode = "persistent"
    vm_device.device.unitNumber = 0
    vm_device.device.controllerKey = 1000
    vm_device.device.capacityInKB = 1024 * 1024
    vm_config = vim.vm.ConfigSpec(name=vm_name, memoryMB=1024, numCPUs=1, files=vm_file, guestId='ubuntu64Guest',
                                  version='vmx-14', deviceChange=[vm_device])
    task = vm_folder.CreateVM_Task(config=vm_config, pool=resource_pool)
    await asyncio.sleep(1)
    print("Creating VM...")
    await asyncio.sleep(5)
    print("Task info: {}".format(task.info))
    await asyncio.sleep(5)
    print("Task result: {}".format(task.info.result))
    await asyncio.sleep(5)
    print("VM created successfully!")
    si.Disconnect()


async def async_search_vm():
    si = SmartConnectNoSSL(host='your_host', user='your_user', pwd='your_password')
    content = si.RetrieveContent()
    container = content.viewManager.CreateContainerView(content.rootFolder, [vim.VirtualMachine], True)
    loop = asyncio.get_event_loop()
    vm_list = await loop.run_in_executor(None, container.view)
    for vm in vm_list:
        if vm.name == 'your_vm_name':
            return vm
    Disconnect(si)


if __name__ == '__main__':
    asyncio.run(create_vm())
